<template>
  <view class="login-container">
    <!-- 图标 -->
    <view class="icon"><uni-icons type="contact-filled" size="100"></uni-icons></view>
    <!-- 登录按钮 -->
    <button class="login-btm" @click="getUserInfo">一键登录</button>
    <!-- 小提示 -->
    <text class="tips">登陆后尽享更多权益</text>
  </view>
</template>

<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {};
  },
  computed: {
    ...mapState('user', ['rediectInfo'])
  },
  methods: {
    getUserInfo(e) {
      uni.getUserInfo({
        provider: 'weixin',
        success: info => {
          this.getToken(info);
          this.$store.commit('user/updateUserInfo', info.userInfo);
        },
        fail: err => {
          uni.$showMsg('您取消了授权');
        }
      });
    },
    async getToken(info) {
      const [err, res] = await uni.login().catch(err => err);
      if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败');
      const { encryptedData, iv, rawData, signature } = info;
      const query = {
        code: res.code,
        encryptedData,
        iv,
        rawData,
        signature
      };
      const msg = await uni.$http.post('/api/public/v1/users/wxlogin', query);
      if (msg.statusCode !== 200) return uni.$showMsg('登陆失败');
      uni.$showMsg('登录成功');
      this.navigateBack();
      this.$store.commit('user/saveToken', msg.data.meta.msg);
    },
    navigateBack() {
      if (this.rediectInfo && this.rediectInfo.openType === 'switchTab') {
        uni.switchTab({
          url: this.rediectInfo.from,
          complete: () => {
            this.$store.commit('user/updataRediectInfo', null);
          }
        });
      }
    }
  }
};
</script>

<style lang="scss">
html,
body {
  background-color: #fff;
}
.login-container {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  overflow: hidden;
  background-color: #efefef;
  .icon {
    height: 200px;
    display: flex;
    align-items: flex-end;
    margin-bottom: 10px;
  }
  .login-btm {
    height: 50px;
    width: 90vw;
    border-radius: 25px;
    background-color: #c00000;
    font-size: 18px;
    color: #fff;
    .login-txt {
    }
  }
  .tips {
    margin-top: 10px;
    font-size: 12px;
    color: gray;
  }
  &::after {
    content: '';
    display: block;
    width: 100%;
    height: 40px;
    background-color: #fff;
    margin-top: 40px;
    border-radius: 100%;
    transform: translateY(50%);
  }
}
</style>
